package com.iotechn.unimall.app.api.userShop;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.Const;
import com.iotechn.unimall.core.annotation.HttpMethod;
import com.iotechn.unimall.core.exception.AppServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.AreaDO;
import com.iotechn.unimall.data.domain.UserShopDO;
import com.iotechn.unimall.data.dto.SpuUserDTO;
import com.iotechn.unimall.data.mapper.AreaMapper;
import com.iotechn.unimall.data.mapper.UserShopMapper;
import com.iotechn.unimall.data.model.Page;
import com.iotechn.unimall.data.util.SessionUtil;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
public class UserShopServiceImpl implements UserShopService {
    @Autowired
    private UserShopMapper userShopMapper;
    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private StringRedisTemplate userRedisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserShopDO create(UserShopDO userShopDO, Long userId, String accessToken) throws ServiceException {
        Date now = new Date();
        userShopDO.setGmtCreate(now);
        userShopDO.setGmtUpdate(now);
        userShopDO.setAdminId(userId);
        if (userShopDO.getAreaId() != null) {
            AreaDO areaDO = areaMapper.selectById(userShopDO.getAreaId());
            if (areaDO != null) {
                userShopDO.setArea(areaDO.getAreaName());
            }
        }
        SpuUserDTO user = SessionUtil.getSpuUser();

        if (userShopMapper.insert(userShopDO) > 0) {
            //创建好门店的同时生成账户信息
            //更新SESSION缓存
            user.setUserShopDO(userShopDO);
            userRedisTemplate.opsForValue().set(Const.SPU_USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(user));
            userShopDO.setId(userShopDO.getId());
            return userShopDO;
        }
        throw new AppServiceException(ExceptionDefinition.USER_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserShopDO update(String accessToken, UserShopDO userShopDO, Long userId) throws ServiceException {
        UserShopDO userShopDO1 = userShopMapper.getUserShopByUserId(userId);
        SpuUserDTO user = SessionUtil.getSpuUser();

        if (userShopDO1 == null) {
            Date now = new Date();
            userShopDO.setGmtCreate(now);
            userShopDO.setGmtUpdate(now);
            userShopDO.setAdminId(userId);

            userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(user));
            if (userShopMapper.insert(userShopDO) > 0) {
                //更新SESSION缓存
                user.setUserShopDO(userShopDO);
                userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(user));
            }
            return userShopDO;
        }
        userShopDO.setId(userShopDO1.getId());
        Date now = new Date();
        userShopDO.setGmtUpdate(now);
        if (userShopMapper.updateById(userShopDO) > 0) {
            //更新SESSION缓存
            user.setUserShopDO(userShopDO);
            userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(user));
            return userShopDO;
        }
        throw new AppServiceException(ExceptionDefinition.USER_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long userId) throws ServiceException {
        UserShopDO userShopDO = userShopMapper.getUserShopByUserId(userId);
        if (userShopDO == null) {
            return "ok";
        }
        if (userShopMapper.deleteById(userShopDO.getId()) > 0) {
            return "ok";
        }
        throw new AppServiceException(ExceptionDefinition.USER_UNKNOWN_EXCEPTION);

    }

    @Override
    public UserShopDO detailById(Long id) throws ServiceException {
        return userShopMapper.selectById(id);
    }


    @Override
    public UserShopDO detailByUserId(Long userId) throws ServiceException {
        return userShopMapper.getUserShopByUserId(userId);
    }

    @HttpMethod(description = "列表")
    public Page<UserShopDO> list(String shopName, Integer page, Integer limit
    ) throws ServiceException {
        Wrapper<UserShopDO> wrapper = new EntityWrapper<UserShopDO>();
        if (!StringUtils.isEmpty(shopName)) {
            wrapper.like("shop_name", shopName);
        }
        wrapper.orderBy("id", false);
        Integer count = userShopMapper.selectCount(wrapper);
        List<UserShopDO> ActiveInfoDOS = userShopMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        return new Page<>(ActiveInfoDOS, page, limit, count);
    }
}
